﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web.Mvc;
using Viettel.VOFFICE.DAO.Models;
using Viettel.VOFFICE.Web.Helpers;
using Viettel.VOFFICE.Web.Models;
using Viettel.VOFFICE.util;

namespace Viettel.VOFFICE.Web.Controllers
{
    public class TodoController : BaseController
    {
        /// <summary>
        /// Thêm công việc
        /// </summary>
        /// <param name="todo"> </param>
        /// <returns></returns>
        [HttpPost]
        [ActionName("add_todo")]
        [ValidateJsonAntiForgeryToken(Salt = AppConstants.TokenSalt)]
        public JsonResult AddNode(TodoModel todo)
        {
            try
            {
                List<ValidationResult> outError;
                if (todo.IsValid(out outError))
                {
                    var dbTodo = new Todo
                    {
                        Name = todo.Name,
                        Description = todo.Description,
                        IsActive = todo.IsActive,
                        CreatedAt = DateTime.Now,
                        UpdatedAt = DateTime.Now,
                        LibraryId =  todo.LibraryId == null || todo.LibraryId == 0 ? null : todo.LibraryId,
                        IsCheckList = todo.IsCheckList,
                        DocTemplate = todo.DocTemplate,
                        NodeId =  todo.NodeId
                    };
                    unitOfWork.TodoRepository.Insert(dbTodo);
                    return Json(SimplyResponse.ResposeWithId(dbTodo.Id));
                }
                else
                {
                    return Json(new JsonResponse()
                    {
                        Status = false,
                        Result = string.Join(", ", outError.Select(o => o.ErrorMessage).ToArray())
                    });
                }//end ìf
            }
            catch (Exception)
            {
                return Json(SimplyResponse.Response200());
                //throw;
            }
        }

        [HttpPost]
        [ActionName("delete_todo")]
        [ValidateJsonAntiForgeryToken(Salt = AppConstants.TokenSalt)]
        public JsonResult DeleteTodo(int id)
        {
            try
            {
                unitOfWork.TodoRepository.Delete(id);
                return Json(SimplyResponse.Response200());
            }
            catch (Exception)
            {
                return Json(SimplyResponse.Response500());
                throw;
            }
        }
    }
}
